package com.example.backend.repository;

import com.example.backend.domain.entity.SystemNotification;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.time.Instant;
import java.util.List;

/**
 * 系统通知Repository
 */
public interface SystemNotificationRepository extends JpaRepository<SystemNotification, Long> {
    
    // 根据类型查找通知
    Page<SystemNotification> findByType(String type, Pageable pageable);
    
    // 根据发送状态查找通知
    Page<SystemNotification> findByIsSent(Boolean isSent, Pageable pageable);
    
    // 根据收件人查找通知
    Page<SystemNotification> findByRecipient(String recipient, Pageable pageable);
    
    // 复合查询
    Page<SystemNotification> findByTypeAndIsSent(String type, Boolean isSent, Pageable pageable);
    Page<SystemNotification> findByTypeAndIsSentAndRecipient(String type, Boolean isSent, String recipient, Pageable pageable);
    
    // 查找待发送的通知
    List<SystemNotification> findByIsSentFalseAndScheduledAtLessThanEqual(Instant now);
    
    // 查找重试次数未达到最大值的失败通知
    @Query("SELECT n FROM SystemNotification n WHERE n.isSent = false AND n.retryCount < n.maxRetries")
    List<SystemNotification> findFailedNotificationsForRetry();
    
    // 统计通知数量
    long countByType(String type);
    long countByIsSent(Boolean isSent);
    long countByCreatedAtBetween(Instant start, Instant end);
    
    // 获取所有类型
    @Query("SELECT DISTINCT n.type FROM SystemNotification n ORDER BY n.type")
    List<String> findAllTypes();
}
